package org.jinyan.wechat.utils;

import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jinyan.utils.CommonUtils;
import org.jinyan.wechat.model.WechatMessage;
import org.jinyan.wechat.model.WechatReply;

/**
 * 微信相关工具类
 */
public class WechatMessageUtil {

	/**
	 * 存储数据的Map转换为对应的Message对象
	 * 
	 * @param map
	 *            存储数据的map
	 * @return 返回对应Message对象
	 */
	public static WechatMessage mapToMessage(Map<String, String> map) {
		System.out.println("存储数据的Map转换为对应的Message对象 start");
		if (map == null) {
			return null;
		}

		String msgType = map.get("MsgType");
		WechatMessage message = new WechatMessage();
		message.setToUserName(map.get("ToUserName"));
		message.setFromUserName(map.get("FromUserName"));
		message.setCreateTime(CommonUtils.convertDtToChar14(new Date(Long.parseLong(map.get("CreateTime")))));
		message.setMsgType(msgType);
		message.setMsgId(map.get("MsgId"));
		message.setInsertDT(CommonUtils.convertDtToChar14(new Date()));
		message.setIsDelete("N");
		if (msgType.equals(WechatMessage.TEXT)) {
			message.setContent(map.get("Content"));
		} else if (msgType.equals(WechatMessage.IMAGE)) {
			message.setPicUrl(map.get("PicUrl"));
		} else if (msgType.equals(WechatMessage.LINK)) {
			message.setTitle(map.get("Title"));
			message.setDescription(map.get("Description"));
			message.setUrl(map.get("Url"));
		} else if (msgType.equals(WechatMessage.LOCATION)) {
			message.setLocationX(map.get("Location_X"));
			message.setLocationY(map.get("Location_Y"));
			message.setScale(map.get("Scale"));
			message.setLabel(map.get("Label"));
		} else if (msgType.equals(WechatMessage.EVENT)) {
			message.setDoEvent(map.get("Event"));
			message.setEventKey(map.get("EventKey"));
		}
		System.out.println("存储数据的Map转换为对应的Message对象 end ");
		return message;
	}

	/**
	 * 解析request中的xml 并将数据存储到一个Map中返回
	 * 
	 * @param request
	 */
	public static Map<String, String> parseXmlToMap(HttpServletRequest request) {
		System.out.println(" parseXmlToMap request中的xml to Map  start");
		Map<String, String> map = new HashMap<String, String>();
		try {
			InputStream inputStream = request.getInputStream();
			SAXReader reader = new SAXReader();
			Document document = reader.read(inputStream);
			Element root = document.getRootElement();
			List<Element> elementList = root.elements();
			for (Element e : elementList)
				// 遍历xml将数据写入map
				map.put(e.getName(), e.getText());
			inputStream.close();
			inputStream = null;
		} catch (Exception e) {
			System.out.println("解析request中的xml 出错" + e.getLocalizedMessage());
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		System.out.println(" parseXmlToMap request中的xml to Map  end");
		return map;
	}

	/**
	 * sha1加密算法
	 * 
	 * @param key需要加密的字符串
	 * @return 加密后的结果
	 */
	public static String sha1(String key) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			md.update(key.getBytes());
			String pwd = new BigInteger(1, md.digest()).toString(16);
			return pwd;
		} catch (Exception e) {
			e.printStackTrace();
			return key;
		}
	}

	public static String replyToXml(WechatReply reply) {
		String replyXML = "<xml><ToUserName><![CDATA[%s]]></ToUserName>"
				+ "<FromUserName><![CDATA[%s]]></FromUserName>"
				+ "<CreateTime>%s</CreateTime>"
				+ "<MsgType><![CDATA[%s]]></MsgType>"
				+ "<Content><![CDATA[%s]]></Content></xml>";
		String type = reply.getMsgType();
		if (WechatReply.TEXT.equals(type)) {
			replyXML = String.format(replyXML, reply.getToUserName(),
					reply.getFromUserName(), reply.getCreateTime(),
					reply.getMsgType(), reply.getContent());

		}

		return replyXML;
	}
}
